package ssm.blog.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import ssm.blog.entity.User;
import ssm.blog.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: lyon
 * @description: shiro权限管理
 * @author: Lyon
 * @create: 2018-05-31 15:31
 **/
public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    /**
     * 为当前登陆的用户授予角色和权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //现在不提供注册功能所以就只有管理员一个人 不存在权限问题
        return null;
    }

    /**
     * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String username=(String)authenticationToken.getPrincipal();
        //从数据库中查询用户信息
        List<User> users=userService.getUserByUsername(username);
        if(users!=null&&users.size()!=0){
            User user=users.get(0);
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", user);
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
                    user.getUsername(), user.getPassword(), "MyRealm");
            return authcInfo;
        }else {
            return null;
        }
    }
}
